package com.gw.yunke.service.impl;

import com.github.pagehelper.PageHelper;
import com.gw.yunke.constant.GlobalConstant;
import com.gw.yunke.dao.CollectMapper;
import com.gw.yunke.dao.CourseMapper;
import com.gw.yunke.dao.ImageMapper;
import com.gw.yunke.dao.InstituteMapper;
import com.gw.yunke.dao.SpecialtyMapper;
import com.gw.yunke.dao.UserMapper;
import com.gw.yunke.domain.*;
import com.gw.yunke.domain.dto.CollectReq;
import com.gw.yunke.domain.dto.CollectResp;
import com.gw.yunke.domain.dto.CourseModifyReq;
import com.gw.yunke.domain.dto.CourseQueryResp;
import com.gw.yunke.domain.dto.CourseQueryReq;
import com.gw.yunke.domain.dto.CourseRankReq;
import com.gw.yunke.domain.dto.UserReq;
import com.gw.yunke.service.ICollectService;
import com.gw.yunke.service.ICourseService;
import com.gw.yunke.service.ISectionService;
import com.gw.yunke.service.IUserService;
import com.gw.yunke.utils.MiscUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static com.gw.yunke.utils.MiscUtils.*;

@Service
public class CourseServiceImpl implements ICourseService {

  private static final Logger log = LoggerFactory.getLogger(CourseServiceImpl.class);

  @Autowired
  private CourseMapper courseMapper;

  @Autowired
  private ISectionService sectionService;

  @Autowired
  private ImageMapper imageMapper;

  @Autowired
  private UserMapper userMapper;

  @Autowired
  private IUserService userService;

  @Autowired
  private SpecialtyMapper specialtyMapper;

  @Autowired
  private InstituteMapper instituteMapper;

  @Autowired
  private ICollectService collectService;

  @Autowired
  private GlobalConstant globalConstant;

  //@CacheEvict(value = "courses", allEntries = true)
  public int createOrUpdateCourse(Course course) {
    int result = 0;
    if (course.getId() == null) {
      result = courseMapper.insertSelective(course);
    } else {
      result = courseMapper.updateByPrimaryKeySelective(course);
    }

    if (result <= 0) {
      log.error("插入课程失败");
    }
    return result;
  }

  //@Cacheable(value = "courses", key = "id")
  public List<CourseQueryResp> getCourseByUserId(Long userId,String courseCode) {
    CourseExample courseExample = new CourseExample();
    CourseExample.Criteria criteria = courseExample.createCriteria();
    criteria.andUserIdEqualTo(userId);
    List<CourseQueryResp> courseQueryRespList = new ArrayList<>();
    List<Course> courseList = courseMapper.selectByExample(courseExample);
    for (Course course : courseList) {
      CourseQueryResp courseQueryResp = new CourseQueryResp();
      courseQueryResp.setId(course.getId().toString());
      courseQueryResp.setName(course.getName());
      System.out.println("++++++++++++ "+ course.getPublish());
      courseQueryResp.setPublish(course.getPublish());
      if (!StringUtils.isEmpty(courseCode) ){
        courseQueryResp.setDescription(course.getDescription());

        courseQueryResp.setSectionList(sectionService.getSectionRespsByCourseId(course.getId()));

      } else if (course.getDescription().length() > 35) {
        courseQueryResp.setDescription(course.getDescription().substring(0, 35) + "...");
      } else
        courseQueryResp.setDescription(course.getDescription());

      //SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
      if(course.getAllTime() != null)
        courseQueryResp.setAllTime(MiscUtils.timeTOSecode(course.getAllTime()));
      else
        courseQueryResp.setAllTime(0L);
      courseQueryResp.setLikeAmount(course.getLikeAmount());
      courseQueryResp.setType(course.getType());
      courseQueryResp.setCode(course.getCode());
      if(course.getTime() > 0)
        courseQueryResp.setRank(course.getRank()/course.getTime());
      else
        courseQueryResp.setRank(5);
      courseQueryResp.setHint(course.getHint());
      //courseQueryResp.setCreaterId(course.getUserId());
      //courseQueryResp.setCreaterName(user.getName());
      if (!StringUtils.isEmpty(course.getSpecialty())) {
        SpecialtyExample example = new SpecialtyExample();
        SpecialtyExample.Criteria criteriaSpec = example.createCriteria();
        criteriaSpec.andCodeEqualTo(course.getSpecialty());
        List<Specialty> specialtyList = specialtyMapper.selectByExample(example);
        if (specialtyList.size() > 0) {
          System.out.println("---" + specialtyList.get(0).getName());
          courseQueryResp.setSpecialtyName(specialtyList.get(0).getName() + "系");
        } else {
          log.info("系不存在", course.getInstitute());
        }
      }

      if (!StringUtils.isEmpty(course.getInstitute())) {
        InstituteExample example = new InstituteExample();
        InstituteExample.Criteria criteriaSpec = example.createCriteria();
        criteriaSpec.andCodeEqualTo(course.getInstitute());
        List<Institute> instituteList = instituteMapper.selectByExample(example);
        if (instituteList.size() > 0) {
          System.out.println("---" + instituteList.get(0).getName());
          courseQueryResp.setInstituteName(instituteList.get(0).getName());
        } else {
          log.info("学院不存在", course.getInstitute());
        }
      }

      if (!isNull(course.getImageId())) {
        courseQueryResp.setImageId(course.getImageId().toString());
        System.out.println("++++++ +   " + globalConstant.getDomain());
        courseQueryResp.setImageReqPath(globalConstant.getDomain() + "/yunke/course/image/" + course.getImageId());
      }

      courseQueryRespList.add(courseQueryResp);
    }

    //courseQueryResp.setSectionList(sectionService.getSectionsByCourseId(id));
    return courseQueryRespList;
  }


  public List<CourseQueryResp> getCourseByExample(CourseQueryReq courseQueryReq) {

    List<CourseQueryResp> courseQueryRespList = new ArrayList<CourseQueryResp>();

    CourseExample courseExample = new CourseExample();
    CourseExample.Criteria criteria = courseExample.createCriteria();
    criteria.andPublishEqualTo(true);
    if (!isEmpty(courseQueryReq.getName())) {
      criteria.andNameLike(courseQueryReq.getName() + "%");
    }
    if (!isEmpty(courseQueryReq.getCreaterName())) {
      UserExample userExample = new UserExample();
      UserExample.Criteria criteriaUser = userExample.createCriteria();
      criteriaUser.andNameLike(courseQueryReq.getCreaterName() + "%");

      List<User> userList = userMapper.selectByExample(userExample);

      List<Long> userIds = new ArrayList<Long>();
      for (User user : userList) {
        userIds.add(user.getId());
      }
      criteria.andUserIdIn(userIds);

    }
    if (!StringUtils.isEmpty(courseQueryReq.getInstitute())) {
      criteria.andInstituteEqualTo(courseQueryReq.getInstitute());
    }
    if (!StringUtils.isEmpty(courseQueryReq.getSpecialty())) {
      criteria.andSpecialtyEqualTo(courseQueryReq.getSpecialty());
    }
    if (!StringUtils.isEmpty(courseQueryReq.getCode())) {
      criteria.andCodeEqualTo(courseQueryReq.getCode());
    }

    courseExample.setOrderByClause("create_time desc");
    PageHelper.startPage(courseQueryReq.getPageNum(), courseQueryReq.getPageSize());
    List<Course> courseList = courseMapper.selectByExample(courseExample);

    if (courseList.size() > 0) {

      for (Course course : courseList) {
        CourseQueryResp courseQueryResp = new CourseQueryResp();
        courseQueryResp.setId(course.getId().toString());
        courseQueryResp.setName(course.getName());
        courseQueryResp.setPublish(course.getPublish());
        if (courseQueryReq.getUserId() != null) {
          CollectReq collectReq = new CollectReq();
          collectReq.setCourseId(course.getId());
          collectReq.setUserId(courseQueryReq.getUserId());
          List<CollectResp> collectResps = collectService.getCollects(collectReq);
          if (collectResps.size() > 0)
            courseQueryResp.setHasCollect((byte) 1);
          else
            courseQueryResp.setHasCollect((byte) 0);
        }
        if (!StringUtils.isEmpty(courseQueryReq.getCode())) {
          courseQueryResp.setDescription(course.getDescription());

          courseQueryResp.setSectionList(sectionService.getSectionRespsByCourseId(course.getId()));

        } else if (course.getDescription().length() > 35) {
          courseQueryResp.setDescription(course.getDescription().substring(0, 35) + "...");
        } else
          courseQueryResp.setDescription(course.getDescription());

        //SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        if(course.getAllTime() != null)
          courseQueryResp.setAllTime(MiscUtils.timeTOSecode(course.getAllTime()));
        else
          courseQueryResp.setAllTime(0L);
        courseQueryResp.setLikeAmount(course.getLikeAmount());
        courseQueryResp.setType(course.getType());
        courseQueryResp.setCode(course.getCode());
        if(course.getTime() > 0)
          courseQueryResp.setRank(course.getRank()/course.getTime());
        else
          courseQueryResp.setRank(5);
        courseQueryResp.setHint(course.getHint());
        //courseQueryResp.setCreaterId(course.getUserId());
        User user = userMapper.selectByPrimaryKey(course.getUserId());
        user.setPassword("*");
        courseQueryResp.setUser(user);
        //courseQueryResp.setCreaterName(user.getName());
        if (!StringUtils.isEmpty(course.getSpecialty())) {
          SpecialtyExample example = new SpecialtyExample();
          SpecialtyExample.Criteria criteriaSpec = example.createCriteria();
          criteriaSpec.andCodeEqualTo(course.getSpecialty());
          List<Specialty> specialtyList = specialtyMapper.selectByExample(example);
          if (specialtyList.size() > 0) {
            System.out.println("---" + specialtyList.get(0).getName());
            courseQueryResp.setSpecialtyName(specialtyList.get(0).getName() + "系");
          } else {
            log.info("系不存在", course.getInstitute());
          }
        }

        if (!StringUtils.isEmpty(course.getInstitute())) {
          InstituteExample example = new InstituteExample();
          InstituteExample.Criteria criteriaSpec = example.createCriteria();
          criteriaSpec.andCodeEqualTo(course.getInstitute());
          List<Institute> instituteList = instituteMapper.selectByExample(example);
          if (instituteList.size() > 0) {
            System.out.println("---" + instituteList.get(0).getName());
            courseQueryResp.setInstituteName(instituteList.get(0).getName());
          } else {
            log.info("学院不存在", course.getInstitute());
          }
        }

        if (!isNull(course.getImageId())) {
          courseQueryResp.setImageId(course.getImageId().toString());
          System.out.println("++++++ +   " + globalConstant.getDomain());
          courseQueryResp.setImageReqPath(globalConstant.getDomain() + "/yunke/course/image/" + course.getImageId());
        }

        courseQueryRespList.add(courseQueryResp);
      }
    }

    return courseQueryRespList;
  }

  @Override
  public int updateRank(CourseRankReq courseRankReq) {
    Course course = courseMapper.selectByPrimaryKey(courseRankReq.getCourseId());

    return courseMapper.addRank(courseRankReq.getRank(),courseRankReq.getCourseId());
  }

  @Override
  public int addLikeAmount(Long courseId) {
    return courseMapper.addLikeAmount(courseId);
  }

  @Override
  public int modifyCourse(CourseModifyReq courseModifyReq) {
    User user = null;
    if(courseModifyReq.getName() != null) {
      UserReq userReq = new UserReq();
      userReq.setName(courseModifyReq.getName());
      user = userService.getUserByExample(userReq).get(0);
    }
    Course course = new Course();
    BeanUtils.copyProperties(courseModifyReq,course);
    if(user != null)
      course.setUserId(user.getId());
    if(courseModifyReq.getPublish() != null && courseModifyReq.getPublish() > 0)
      course.setPublish(true);
    else
      course.setPublish(false);

    return courseMapper.updateByPrimaryKeySelective(course);
  }

  public List<Course> queryCourses(CourseQueryReq courseQueryReq) {
    return null;
  }
}
